package com.kzw.oa.misc.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ExportWordUtil {

	public static void exportWord(HttpServletRequest req, HttpServletResponse resp, 
			String fileName,
			String ftlName,
			Map<String, Object> dataMap) throws Exception {
		
		String path = req.getSession().getServletContext().getRealPath("/pages/word");
		Configuration cfg = new Configuration();
		cfg.setDefaultEncoding("utf-8");
		cfg.setDirectoryForTemplateLoading(new File(path));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		Template temp = cfg.getTemplate(ftlName);
		temp.setEncoding("utf-8");

		// 将模板和数据模型合并生成文件
		File tmpfile = File.createTempFile("kzw_", ".doc");// 创建一个临时文件
		Writer docout = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(tmpfile)));
		try {
			temp.process(dataMap, docout);
			docout.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		}

		FileInputStream fis = new FileInputStream(tmpfile);

		OutputStream out = resp.getOutputStream();
		resp.resetBuffer();
		fileName = new String(fileName.getBytes("GBK"), "ISO8859-1");
		resp.setHeader("Content-Disposition", "attachment; filename=\""
				+ fileName + "\"");
		resp.addHeader("Content-Length", tmpfile.length() + "");
		resp.setContentType("application/octet-stream");

		byte[] buf = new byte[4096];
		int len = -1;
		while ((len = fis.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		out.flush();
		out.close();
		fis.close();
		tmpfile.delete();
	}
}
